package com.ruoyi.web.controller.tool;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 计算攻击率的算法
 */
public class CalcUtils {
    public static void main(String[] args) {
        calcGls(10);
    }

    /**
     * 要素链的关联数
     */
    public static List<Rate> calcGls(int n) {
        /**当要素数为时*/

        List<Rate> rates = new ArrayList<>();
        Double k = Math.pow(2.0, n) - 1 - n;
//        System.out.println(k);

        Double allRate = 0.0;
        int test = 0;
        for (int i = 2; i <= n; i++) {

            long ki = getNi(n, i);
            test += ki;

            Double rate = ki / k;
            allRate += rate;
//            System.out.println("正关联要素数：" + i + " 比率：" + point4(ki / k) + " 累计比率：" + point4(allRate));

            Rate r = new Rate("c_"+String.valueOf(i), point4(ki / k), point4(allRate));
            rates.add(r);
        }
//        System.out.println(test);

        return rates;
    }

    //有n个数，任意取i个的组合数目
    private static long getNi(int n, int i) {
        long count = 1;
        for (int j = 0; j < i; j++) {
            count *= (n - j);
        }

        for (int j = 0; j < i; j++) {
            count /= (i - j);
        }
        return count;
    }

    //保留4位小数四舍五入
    public static String point4(double d) {
        DecimalFormat df = new DecimalFormat("0.0000");
        return df.format(d);
    }

}
